package org.example.hypersonaltools.scene;

import javafx.animation.*;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ReadingBookScene extends Scene {

    private final Pane root;
    private final Stage stage;
    private final File selectedImage;
    private final List<String> chapters;
    private String currentChapterTitle;
    private final float speed; // 行/秒
    private final int fontSize;
    private final String fontColor;

    private TextFlow textFlow;
    private ScrollPane scrollPane; // 新增：滚动容器
    private Timeline timeline;
    private int ChaptesIndex;
    private final List<Node> textNodes=new ArrayList<>();
    private boolean isPause=true;
    private double xOffset;
    private double yOffset;

    public ReadingBookScene(Pane vBox, Stage stage, File selectedImage,
                            List<String> chapters, String chapterTitle,
                            float speed, int fontSize, String fontColor) {
        super(vBox, 360, 360);
        this.root = vBox;
        this.stage = stage;
        this.selectedImage = selectedImage;
        this.chapters = chapters;
        this.currentChapterTitle = chapterTitle;
        this.speed = speed;
        this.fontSize = fontSize;
        this.fontColor = fontColor;

        this.setFill(null);
        initializeUI();
        setupEventListeners();
        startTextAnimation();
    }

    private void setupEventListeners() {

        Button close = new Button("X");
        close.setOnAction(e -> {
            if (timeline != null)
                timeline.stop();
            stage.close();
        });
        Background backOne = new Background(new BackgroundFill(Color.color(1,1,1,0.5), CornerRadii.EMPTY, Insets.EMPTY));
        Background backTwo = new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY));
        close.setBackground(backTwo);

        root.getChildren().add(close);

        Button pause = new Button("pause");
        pause.setOpacity(0);
        pause.setLayoutX(180);
        pause.setOnMouseClicked(actionEvent -> {
            if (isPause){
                timeline.pause();
                isPause=false;
            }else {
                timeline.play();
                isPause=true;
            }
        });
        pause.setOnMouseEntered(mouseEvent -> pause.setOpacity(1));
        pause.setOnMouseExited(mouseEvent -> pause.setOpacity(0));
        root.getChildren().add(pause);

        Button next = new Button("next");
        next.setOpacity(0);
        next.setLayoutX(350);
        next.setOpacity(180);
        next.setOnMouseClicked(actionEvent -> {

        });

        root.setOnMouseEntered(mouseEvent -> root.setBackground(backOne));

        root.setOnMousePressed(event -> {
            // 记录鼠标按下时的位置偏移
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
        });

        root.setOnMouseDragged(event -> {
            // 根据鼠标移动更新窗口位置
            stage.setX(event.getScreenX() - xOffset);
            stage.setY(event.getScreenY() - yOffset);

        });

        root.setOnMouseReleased(mouseDragEvent -> root.setBackground(backTwo));
    }

    private void initializeUI() {
        Screen screen = Screen.getPrimary();
        stage.setX(screen.getBounds().getWidth() - 360);
        stage.setY(screen.getBounds().getHeight() - 360);
        root.setStyle("-fx-background-color: transparent;");

        ImageView bgImage = new ImageView(new Image(selectedImage.toURI().toString()));
        bgImage.setFitWidth(root.getWidth());
        bgImage.setFitHeight(root.getHeight());
        bgImage.setOpacity(0.8);
        bgImage.setPreserveRatio(false);

        root.getChildren().setAll(bgImage);

        // 滚动容器设置
        textFlow = new TextFlow();
        textFlow.setStyle("-fx-background-color: transparent; -fx-max-width: 200; -fx-max-height: 200;");
        textFlow.setBackground(Background.EMPTY); // 双重保险

        scrollPane = new ScrollPane(textFlow);
        scrollPane.setStyle(
                "-fx-background-color: transparent;" +
                        "-fx-control-inner-background: transparent;" +
                        "-fx-background: transparent;" +
                        "-fx-hbar-policy: never;" +
                        "-fx-vbar-policy: never;"
        );

        scrollPane.setBackground(Background.EMPTY);
        scrollPane.setFitToWidth(true);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setLayoutX(90);
        scrollPane.setLayoutY(90);
        scrollPane.setMaxHeight(180);

        root.getChildren().add(scrollPane);
    }

    private void startTextAnimation() {
        String chapterContent = findChapterByTitle(currentChapterTitle);
        if (chapterContent == null) {
            chapterContent = "未找到章节: " + currentChapterTitle;
        }

        // 分离标题和正文
        String[] parts = chapterContent.split("\n", 2);
        String mainText = parts.length > 1 ? parts[1] : "";

        // 清空初始文本
        textFlow.getChildren().clear();

        // 创建临时Text用于测量
        Text measuringText = new Text();
        measuringText.setFont(Font.font(fontSize));

        // 中文分行逻辑 - 按字符测量
        List<String> lines = new ArrayList<>();
        StringBuilder currentLine = new StringBuilder();

        for (int i = 0; i < mainText.length(); i++) {
            char c = mainText.charAt(i);
            measuringText.setText(currentLine.toString() + c);

            // 如果当前行加上新字符不超过宽度，就添加
            if (measuringText.getLayoutBounds().getWidth() <= 200) { // 200是textFlow的max-width
                currentLine.append(c);
            } else {
                // 超过宽度就换行
                if (!currentLine.isEmpty()) {
                    lines.add(currentLine.toString());
                    currentLine = new StringBuilder(String.valueOf(c));
                }
            }

            // 遇到换行符直接换行
            if (c == '\n') {
                lines.add(currentLine.toString());
                currentLine = new StringBuilder();
            }
        }

        // 添加最后一行
        if (!currentLine.isEmpty()) {
            lines.add(currentLine.toString());
        }

        for (int i = 0; i < lines.size(); i++) {
            Text lineText = new Text(lines.get(i) + (i < lines.size()-1 ? "\n" : ""));
            lineText.setFont(Font.font("SimHei", FontWeight.BOLD,fontSize));
            lineText.setFill(Color.web(fontColor));
            textFlow.getChildren().add(lineText);
        }

        //根据行数控制滚动条动画播放速度，比如speed是0.5，那么动画播放速度就应该是1/(lines.size()/0.5)
        // 2. 计算滚动动画参数
        double totalScrollDistance = 1.0; // 从顶部到底部的总距离
        double scrollSpeed = speed * 0.5; // 速度调整系数，可根据需要微调
        double totalDuration = lines.size() / scrollSpeed; // 总持续时间

        // 3. 创建平滑滚动动画
        this.timeline = new Timeline(
                new KeyFrame(Duration.ZERO, new KeyValue(scrollPane.vvalueProperty(), 0.0)),
                new KeyFrame(Duration.seconds(totalDuration),
                        new KeyValue(scrollPane.vvalueProperty(), totalScrollDistance, Interpolator.LINEAR))
        );
        this.timeline.setCycleCount(1);

        // 4. 启动动画
        this.timeline.play();

        this.timeline.setOnFinished(actionEvent -> {
            this.startTextAnimation();
        });

//        // 5. 透明度效果处理
        System.out.println(textFlow.getChildren().size());
        textNodes.clear();
        textNodes.addAll(new ArrayList<>(textFlow.getChildren()));

        scrollPane.vvalueProperty().addListener((observable, oldValue, newValue) -> {
            Iterator<Node> iterator = textNodes.iterator();
            System.out.println(textNodes.size());
            List<Node> nodes = new ArrayList<>();
            while (iterator.hasNext()) {
                Node node = iterator.next();
                double ty = node.getLocalToSceneTransform().getTy();
                if (ty<=80){
                    iterator.remove();
                }else if (ty>80&&ty<270){
                    nodes.add(node);
                }else if (ty>=270){
                    break;
                }
            }
            this.applyOpacityCurve(nodes);
        });
    }

    private void applyOpacityCurve(List<Node> nodes) {
        int n = nodes.size();
        for (int i = 0; i < n; i++) {
            // 标准化x值到[0,1]区间
            double x = (double)i / (n - 1);

            // 使用三角函数创建山峰形曲线
//            double opacity = Math.sin(x * Math.PI); // 0→1→0

            // 或者使用二次函数创建更平缓的曲线
             double opacity = 4 * x * (1 - x); // 0→1→0

            nodes.get(i).setOpacity(opacity);
        }
    }
    private String findChapterByTitle(String title) {
        int index=-1;
        for (String chapter : chapters) {
            index++;
            if (chapter.startsWith(title + "\n")) {
                this.ChaptesIndex=index;
                if (index+2<=chapters.size()){
                    String nextChapter = chapters.get(index + 1);
                    this.currentChapterTitle = nextChapter.substring(0,nextChapter.indexOf("\n"));
                }
                return chapter;
            }
        }
        return null;
    }
}

